<?php

namespace app\common\controller;

use think\cache\driver\Redis;
use think\Controller;
/**
 * 创蓝-短信发送 验证
 */
class SmsChuangLan extends Controller
{

    public $redis = '';
    public function initialize(){

        $this->redis = new Redis(getRedisConfig());
    }
    /**
     * 发送短信
     * @param str $phone 手机号
     * @param str $code 验证码
     * @param str $type 发送类型
     * @param str $sign 签名
     * @return 数据信息| 0 成功 !=0失败
     * @since 2024/09/27
     * @author ZhangXuanNeng
     */
    public function sendSms($phone,$code,$type,$sign,$text){
        $url = 'http://smssh1.253.com/msg/v1/send/json';
        write_log('INFO', 'SmsChuangLan.php', '创蓝平台发送:'.$code, 'sms', true);
        $postArr = array(
            'account'  =>  config('sms.CL_ACCOUNT'),
            'password' => config('sms.CL_PASSWORD'),
            'msg' => '【'.$sign.'】您的验证码是'.$code.$text,
            'phone' => $phone,
            'report' => true,
            'extend'=> rand(1,999),
        );
        if($type == 3){
            $postArr['msg'] = '【'.$sign.'】您的手机已成功注册，密码为'.$code.'，为了账号安全请尽快修改您的密码';
        }
        $postFields = json_encode($postArr);
        $result = $this->sendCurl($url,$postFields);
        if (isset($result['code'])  && $result['code']=='0'){
            $this->redis->set($phone,$code,300);
            return ['code'=>0,'return_code'=>'success','msg'=>'发送成功'];
        } else {
            return ['code'=>-1,'return_code'=>'fail','msg'=>$result['errorMsg']];
        }
    }
    public function sendCurl($url,$postFields){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json; charset=utf-8'
            )
        );
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($ret, TRUE);
        return $result;
    }
}
